/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package thread;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;
import javax.swing.ListModel;
import mediate.Mediate;
import model.ServerSocket_Model;
import view.MainServer_View;

/**
 *
 * @author 马凯
 */
public class Server_Thread extends Thread {

    private static Server_Thread st;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private MainServer_View msv;

    public Server_Thread(Socket socket, MainServer_View msv) {
        this.msv = msv;
        this.socket = socket;
        this.addListDate(socket);
        
        System.out.println("create a new thread");
        ListModel lm = msv.getServerViewModel().getVisitList().getModel();
        
        System.out.println(socket.getInetAddress().toString());
        
        try {
            this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            this.out = new PrintWriter(socket.getOutputStream(), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

@Override
    public void run() {
        try {
            String receive;
            while (!(receive=in.readLine()).isEmpty()) {

        String[] code = receive.split(";");
        switch(Integer.valueOf(code[code.length-1])){
            case 1: Mediate.getInstance(receive, this).run();break;
            case 6: Mediate.getInstance(receive, this).run();break;
            default:
                String output = Mediate.getInstance(receive, this).run();
                out.println(output);
                out.flush();
                break;
            }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    
    public void addListDate(Socket s){
        ListModel lm = msv.getServerViewModel().getVisitList().getModel();
        Vector v = new Vector();
        for(int i=0;i<lm.getSize();i++){
            v.add(i, lm.getElementAt(i));
        }
        v.addElement(socket.getInetAddress().toString()+" is arriving!");
        msv.getServerViewModel().getVisitList().setListData(v);
    }

    public ServerSocket_Model getSocketModel(){
        ServerSocket_Model ssm = new ServerSocket_Model();
        ssm.setIn(in);
        ssm.setOut(out);
        ssm.setSocket(socket);
        return ssm;
    }
}
